package com.zp.configuration;

import com.aliyun.oss.OSS;
import com.aliyun.oss.model.SetBucketCORSRequest;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Objects;

/**
 * 闁告凹鍨版慨鈺呭籍閺堜絻绀?OSS 婵℃鍎奸鏇犵磾?CORS 閻熸瑥瀚崹顖炴晬鐏炶棄甯掗悹浣呵规晶鐘电博椤栨粍绾柟鎭掑劥濞夋洟宕洪悢绋款€欓柛娆愮墪濞存﹢鎮ч崶褑瀚欑紓浣姑崺妤呭礆?canvas闁??
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class OssCorsInitializer {
    private final OSS ossClient;
    private final AliyunOssClient aliyunOssClient;
    private final OssCorsProperties corsProperties;

    @PostConstruct
    public void initCors() {
        String bucket = aliyunOssClient.getBucket();
        try {
            // 濞寸姴閰ｉ崢銈囩磾椤旀鍤㈤柛娆愮墪閸樻垹鎷嬮崨濠冮檷婵犙勫姧缁辨繈寮ㄩ娑樼槷闂侇偅顨呰ぐ鍧楀礆閸℃稒顓鹃柨娑樼焸缁垳鎷嬮妶鍛笒閻犱礁鎲″﹢浼村捶閺夎法鍩楅悷娆庤兌椤忣剟宕?
            List<String> allowedOrigins = safeList(corsProperties.getAllowedOrigins(),
                    Arrays.asList("http://localhost:5173", "http://127.0.0.1:5173"));
            // 闁稿繋娴囬蹇涘棘鐟欏嫮銆婂娑櫱归? GET闁靛棔绗璄AD闁挎稑鐗呯粭澶愬礌閸涱厽鍎?OPTIONS闁??
            List<String> allowedMethods = safeList(corsProperties.getAllowedMethods(), Arrays.asList("GET", "HEAD"));
            // 闁稿繋娴囬蹇旂▔鎼淬垺鐦归梻鍥皺濞堟垹鎷犻柨瀣勾濠??
            List<String> allowedHeaders = safeList(corsProperties.getAllowedHeaders(), Collections.singletonList("*"));
            List<String> exposeHeaders = safeList(corsProperties.getExposeHeaders(), Collections.singletonList("ETag"));
            Integer maxAgeSeconds = corsProperties.getMaxAgeSeconds();
            if (maxAgeSeconds == null || maxAgeSeconds <= 0) {
                maxAgeSeconds = 300;
            }

            SetBucketCORSRequest request = new SetBucketCORSRequest(bucket);
            SetBucketCORSRequest.CORSRule rule = new SetBucketCORSRequest.CORSRule();
            rule.setAllowedOrigins(allowedOrigins);
            rule.setAllowedMethods(allowedMethods);
            rule.setAllowedHeaders(allowedHeaders);
            rule.setExposeHeaders(exposeHeaders);
            rule.setMaxAgeSeconds(maxAgeSeconds);
            request.addCorsRule(rule);

            ossClient.setBucketCORS(request);
            log.info("OSS CORS 鐎瑰憡褰冮崹鍨叏鐎ｎ亜顕? bucket={}, origins={}", bucket, allowedOrigins);
        } catch (Exception e) {
            log.warn("闁告帗绻傞～鎰板礌?OSS CORS 濠㈡儼绮剧憴锕傛晬瀹€鍐惧殲闁革负鍔嶇敮鍫曞礆鐠哄搫閰遍柟闈涱儏婵晠鏌婂鍥╂瀭闁靛棔绻漸cket={}", bucket, e);
        }
    }

    private static <T> List<T> safeList(List<T> fromConfig, List<T> defaultValue) {
        if (fromConfig == null || fromConfig.isEmpty()) {
            return defaultValue;
        }
        // 閺夆晛娲﹂幎銈囩矚閸濆嫬甯楃紒杈╁缁辨繈鐛張闈涒枏闁??Collectors.toList() 濞ｅ洦绻嗛惁澶愬礂閻撳寒鍟囬柟??
        return fromConfig.stream().filter(Objects::nonNull).collect(java.util.stream.Collectors.toList());
    }

}



